<template>
    <div class="page">
        <p>打包图</p>
        <div id="container"></div>
    </div>
</template>
<script>
import * as d3 from "d3"
export default {
    data() {
        return {
            city: {
                name: "中国",
                children: [
                    {
                        name: "浙江",
                        children: [
                            { name: "杭州",value:1 },
                            { name: "宁波",value:2 },
                            { name: "温州",value:3 },
                            { name: "绍兴",value:4 }
                        ]
                    },
                    {
                        name: "广西",
                        children: [
                            {
                                name: "桂林",
                                children: [
                                    { name: "秀峰区" ,value:5},
                                    { name: "叠彩区",value:6 },
                                    { name: "象山区" ,value:7},
                                    { name: "七星区" ,value:8}
                                ]
                            },
                            { name: "南宁" ,value:9},
                            { name: "柳州" ,value:10},
                            { name: "防城港" ,value:11}
                        ]
                    }
                ]
            }
        }
    },
    methods: {
        draw() {
            let svgWidth = 800,
                svgHeight = 800,
                colors = d3.schemeCategory10;
            this.svg = d3
                .select("#container")
                .append("svg")
                .attr("width", svgWidth)
                .attr("height", svgHeight)
            let root = d3
                    .hierarchy(this.city)
                    .sum(d => d.value)
                    .sort((a, b) => b.value - a.value),
                packLayout = d3.pack().size([400, 400])
            packLayout(root)
            console.log(root.descendants())
            let gPack = this.svg.append('g')
            .attr('transform',`translate(${svgWidth/4},${svgHeight/4})`);
            gPack.selectAll('circle')
            .data(root.descendants())
            .join('circle')
            .attr('class',d=>d.children?'node':'leafnode')
            .attr('cx',d=>d.x)
            .attr('cy',d=>d.y)
            .attr('r',d=>d.r)
            .attr('fill',(d)=>colors[d.height])
            gPack.selectAll('text')
            .data(root.descendants())
            .join('text')
            .style('fill-opacity',d=>d.children?0:1)
            .attr('x',d=>d.x)
            .attr('y',d=>d.y)
            .attr('dy','.3em')
            .text(d=>d.data.name)
            .attr('fill','#fff')
            .attr('font-size',12)
            .attr('text-anchor','middle')
        }
    },
    mounted() {
        this.draw()
    }
}
</script>
